package com.lxyk.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxyk.yygh.cmn.listener.DictListener;
import com.lxyk.yygh.cmn.mapper.DictMapper;
import com.lxyk.yygh.cmn.service.DictService;
import com.lxyk.yygh.model.cmn.Dict;
import com.lxyk.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    /**
     * 根据id查询子数据列表
     * @param id
     * 使用@Cacheable注解时，如果在方法被调用时，缓存中存在与给定的缓存key匹配的数据，
     * 则直接从缓存中返回数据，而不会执行方法体。当缓存中没有匹配的数据时，
     * 则执行方法体，并将结果存储在缓存中，以便下次使用。
     */
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChlidData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> list = baseMapper.selectList(wrapper);
        //向每个集合中的对象设置 hasChildren
        for (Dict dict : list) {
            Long dictId = dict.getId();
            boolean children = this.isChildren(dictId);
            dict.setHasChildren(children);
        }
        return list;
    }
    //判断id下面是否有之节点
    private boolean isChildren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }

    /**
     * 导出
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //下载信息和头信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

            //查询数据库
            List<Dict> dictList = baseMapper.selectList(null);
            List<DictEeVo> dictEeVoList = new ArrayList<>();
            for (Dict dict : dictList) {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict,dictEeVo);
                dictEeVoList.add(dictEeVo);
            }
            //调用方法进行写操作
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("数据字典").doWrite(dictEeVoList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入
     * @param file
     */
    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //根据 dictCode和value查询
    @Override
    public String getDictName(String dictCode, String value) {
        //如果dictCode为空，就直接根据value查
        if(StringUtils.isEmpty(dictCode)){
            //value查询
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            if(null!=dict){
                return dict.getName();
            }
        }else{
            //如果不为空，根据dictCode和value查
            //dictCode获取新的dict对象 得到id值
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
            Long parent_id = dict.getId();
            //id和value查询
            Dict findDict = baseMapper
                    .selectOne(new QueryWrapper<Dict>()
                            .eq("parent_id", parent_id)
                            .eq("value", value));
            if(null!=findDict){
                return findDict.getName();
            }
        }
        return "";
    }

    /**
     * 根据dictCode查询下级节点
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictCode获取对应的id
        Dict codeDict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
        //根据id获取子节点
        if(null == codeDict) return null;
        return this.findChlidData(codeDict.getId());
    }
}
